import Taro from "@tarojs/taro"
import { View } from "@tarojs/components"
import { Button } from "@antmjs/vantui"
import { useDispatch } from 'react-redux'
import { updateUserInfo, updateToken } from '../../store/module/user'

const WowLogin = () => {

  // redux
  const disPatch = useDispatch()

  // methods

  const getUserInfo = () => {
    return new Promise((resolve, reject) => {
      Taro.getUserProfile({
        desc: '登录',
        success: res => {
          resolve(res)
        },
        fail: err => {
          reject(err)
        }
      })
    })
      .then(res => res)
      .catch(err => err)
  }

  const login = async () => {
    const userRes = await getUserInfo()
    if (userRes.errMsg !== 'getUserProfile:ok') return Taro.$showMsg('您取消了登录授权')

    const loginRes = await Taro.login()
    if (loginRes.errMsg !== 'login:ok') return Taro.$showMsg('登录失败')

    const tokenRes = await Taro.$http.post('/api/gy/login', {
      jsCode: loginRes.code,
      vname: userRes.userInfo.nickName
    })
    console.log(tokenRes)
    if (tokenRes.errMsg || tokenRes.data.code !== 0) return Taro.$showMsg('登录失败')
    disPatch(updateUserInfo(userRes.userInfo))
    disPatch(updateToken(tokenRes.data.token))
  }

  return (
    <View onClick={login} className='login'>点击登录</View>
  )
}

export default WowLogin